//
//  ST_BTCaptchaController.swift
//  BTVideo
//
//  Created by DouLei on 2019/7/9.
//  Copyright © 2019 DouLei. All rights reserved.
//

import UIKit
import MBProgressHUD
import HandyJSON
import SwifterSwift
import SwiftyUserDefaults

class ST_BTCaptchaController: UIViewController {

    // MARK: - set value from outside
    var phone_number = ""
    
    var bind_phone_number = false
    // MARK: - properties
    
    lazy var captcha_view:ST_BTCaptchaView = {
        let control = ST_BTCaptchaView()
        return control
    }()
    
    lazy var captcha_info_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
      control.setTitleForAllStates("我们已给你发送了一个验证码")
      control.setTitleColor(UIColor.init(hexString: "#333333")!, for: UIControl.State.normal)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.semibold)
      control.setImageForAllStates(ST_ImageUtils.imageName("register_icon_emoji验证码")!)
        control.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 10, bottom: 0, right: 0)
//        control.backgroundColor = Color.random
        return control
    }()
    
    lazy var normal_tips:String = {
       return String.init(format: "验证码已发送至 +86 %@", self.phone_number)
    }()
    
    lazy var other_tips:String = {
       return "重新获取验证码"
    }()
    
    lazy var captcha_sub_label:UILabel = {
        
        let control = UILabel.init()
    
        let str = normal_tips
        
        control.text = str
        
        control.textColor = Color.init(hexString: "#999999")
        
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)
        
        return control
    }()
    
    lazy var re_fresh_captch_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setTitleColor(Color.white, for: UIControl.State.normal)
        control.setTitleForAllStates("重新获取")
        control.cornerRadius = 16
        control.backgroundColor = Color.init(hexString: "#FEC207")
//        control.borderWidth = 1
//        control.borderColor = Color.init(white: 1, alpha: 0.4)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        
        control.add_touch_up(insideTarget: self, action: #selector(re_fresh_captch_handle))
        
        return control
    }()
    
    lazy var next_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)

        control.setImageForAllStates(ST_ImageUtils.imageName("register_bot_下一步")!)
        
        control.setImage(ST_ImageUtils.imageName("register_bot_下一步diss"), for: UIControl.State.disabled)
        
        control.addTarget(self, action: #selector(nextStep), for: UIControl.Event.touchUpInside)
        
        control.isEnabled = false
        
        return control
        
    }()
    
    lazy var previous_action_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)

        control.setImageForAllStates(ST_ImageUtils.imageName("register_bot_上一步")!)
        
        control.addTarget(self, action: #selector(previous_step), for: UIControl.Event.touchUpInside)
        
        
        return control
        
    }()
    
    lazy var count_down_label:UILabel = {
       
        let control = UILabel.init()
        control.textColor = Color.init(hexString: "#999999")
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        return control
    }()
 
    var timer:Timer?
    var currentSeconds = 60
    
    
    // MARK: - life cycle
    
    override func viewWillAppear(_ animated: Bool) {
        
        super.viewWillAppear(animated)
        
        if !bind_phone_number{
            MobClick.beginLogPageView("InputCAPTCHA")
        }
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        if !bind_phone_number{
            MobClick.endLogPageView("InputCAPTCHA")
        }
        
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
    
    
        UIView.zenly_animate(withDelay: 0.25, animations: {
            
            self.captcha_info_btn.x = 20
            
            self.captcha_info_btn.alpha = 1
            
        }) { (f) in
            
        }
        
        UIView.zenly_animate(withDelay: 0.35, animations: {
            
            self.captcha_sub_label.x = 30
            self.captcha_sub_label.alpha = 1
            
        }) { (f) in
            
        }
        
        
        UIView.zenly_animate(withDelay: 0.45, animations: {
            
            self.captcha_view.x = 30
            
        }) { (f) in
            
            UIView.zenly_animate(withDelay: 0, animations: {
                
                self.count_down_label.alpha = 1
                self.next_btn.alpha = 1
                self.previous_action_btn.alpha = 1
                
            }) { (f) in
                
//                UIView.zenly_animate(animations: {
//                    self.next_btn.alpha = 1
//                    self.previous_action_btn.alpha = 1
//                }) { (f) in
//                }
            }
        }
        
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = Color.white
        
        if !bind_phone_number{
            back_thread_execute(afterDelay: 1) {
                ST_RegisterMonitor.shared.logger.report(fromController: self)
            }
        }
        
        //RegisterStepManager.shared.step = 3
        
        view.addSubview(captcha_info_btn)
        captcha_info_btn.frame = CGRect.init(x: 150, y: 73-20+statusBarHeight, width: 265, height: 30)
        captcha_info_btn.alpha = 0.1
        
        view.addSubview(captcha_sub_label)
        captcha_sub_label.frame = CGRect.init(x: 150, y: captcha_info_btn.frame.maxY + 7, width: 300, height: 25)
        captcha_sub_label.alpha = 0.1
        
        
        view.addSubview(captcha_view)
        captcha_view.frame = CGRect.init(x: ScreenWidth, y: captcha_sub_label.frame.maxY + 75, width: 180+50, height: 70)
        
        view.addSubview(count_down_label)
        count_down_label.frame = CGRect.init(x: 30, y: captcha_view.frame.maxY + 18, width: 130, height: 20)
        captcha_sub_label.alpha = 0.1
        
        view.addSubview(re_fresh_captch_btn)
        re_fresh_captch_btn.frame = CGRect.init(x: 30, y: captcha_view.frame.maxY + 20, width: 100, height: 32)
        
        re_fresh_captch_btn.isHidden = true
        
        view.addSubview(next_btn)
        next_btn.frame = CGRect.init(x: ScreenWidth - 45 - 40, y: re_fresh_captch_btn.frame.maxY + 36, width: 45, height: 45)
        next_btn.alpha = 0.1
        
        view.addSubview(previous_action_btn)
        previous_action_btn.frame = CGRect.init(x: 30, y: re_fresh_captch_btn.frame.maxY + 36, width: 45, height: 45)
        previous_action_btn.alpha = 0.1
        
        self.captcha_view.inputAction()
        
        //TianRegisterStepManager.shared.addHelperBtn(root_view: view)
        
        count_down_handler()
        
        self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(count_down_handler), userInfo: nil, repeats: true)
        
        
        self.captcha_view.inputTextStatus = { f in
            self.next_btn.isEnabled = f
        }
    }
    
    
    
    

    @objc func count_down_handler(){
        
        self.currentSeconds -= 1
        
        if self.currentSeconds < 0{
            
            self.captcha_sub_label.text = other_tips
            
            self.re_fresh_captch_btn.isHidden = false
            self.count_down_label.isHidden = true
            self.currentSeconds = 59
            self.timer?.invalidate()
            self.timer = nil
            
        }else{
            
            self.captcha_sub_label.text = normal_tips
            self.re_fresh_captch_btn.isHidden = true
            self.count_down_label.isHidden = false
        }
        
        self.count_down_label.text = String.init(format: "%d秒后可重新获取", self.currentSeconds)
        
    }
    
    @objc func previous_step()  {
        
        self.navigationController?.popViewController()
        
    }
    
    @objc func nextStep()  {
        
        guard let str = self.captcha_view.textField.text else { return  }
        
        
        if bind_phone_number {
            
            ST_MobilePhoneStepDispatcher.shared.check_phone_number(self.phone_number, captcha: str)
            
        }else{
            
            ST_RegisterMonitor.shared.get_started(dict: ["uni_account":self.phone_number,"type":"1","code":str], expectedHudController: self)
        }
        
    }
    
    
    
    
    @objc func re_fresh_captch_handle(){
        
        
        var api = PH.sendCaptchaApi
        
        if bind_phone_number  {
            api = PH.sendCaptchaForBindApi
        }

        
        JVrequest(api, parameters: ["phone":phone_number,"scene":"register"], success: { (json) in
        
            self.currentSeconds = 60
            
            self.count_down_handler()
            
            self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.count_down_handler), userInfo: nil, repeats: true)
            
        }) { (code, str) in
            
//            log.error("登录接口错误",str)
            
            let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
            hud.mode = .text
            hud.label.text = str
            hud.hide(animated: true, afterDelay: 1.5)
            
        }
        
    }
    
}
